<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket测试工具</title>
    <style>
      .container {
        max-width: 800px;
        margin: 20px auto;
        padding: 20px;
      }
      #log {
        height: 400px;
        border: 1px solid #ccc;
        padding: 10px;
        overflow-y: auto;
        margin: 20px 0;
      }
      .controls {
        margin-bottom: 20px;
      }
      button {
        padding: 8px 16px;
        margin-right: 10px;
      }
      input {
        padding: 8px;
        width: 300px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>WebSocket测试工具</h1>
      <div class="controls">
        <input
          type="text"
          id="wsUrl"
          placeholder="WebSocket服务器URL"
          value="ws://localhost:8080"
        />
        <button id="connectBtn">连接</button>
        <button id="disconnectBtn" disabled>断开连接</button>
      </div>
      <div class="controls">
        <input type="text" id="messageInput" placeholder="输入消息" />
        <button id="sendBtn" disabled>发送消息</button>
        <button id="sendRequestBtn" disabled>发送请求并等待响应</button>
      </div>
      <div id="log"></div>
    </div>

    <script type="module">
      import WebSocketClient from './websocket-wrapper.js';

      // DOM元素
      const wsUrlInput = document.getElementById('wsUrl');
      const connectBtn = document.getElementById('connectBtn');
      const disconnectBtn = document.getElementById('disconnectBtn');
      const messageInput = document.getElementById('messageInput');
      const sendBtn = document.getElementById('sendBtn');
      const sendRequestBtn = document.getElementById('sendRequestBtn');
      const logElement = document.getElementById('log');

      let wsClient = null;

      // 日志函数
      function log(message, isError = false) {
        const logEntry = document.createElement('div');
        logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
        if (isError) logEntry.style.color = 'red';
        logElement.appendChild(logEntry);
        logElement.scrollTop = logElement.scrollHeight;
      }

      function init() {
        const url = wsUrlInput.value;
        log(`正在连接到 ${url}...`);
        wsClient = new WebSocketClient(url, {
          reconnectInterval: 2000,
          maxReconnectAttempts: 3,
          heartbeatInterval: 10000,
        });

        // 注册事件监听
        wsClient.on('open', () => {
          log('连接成功');
          connectBtn.disabled = true;
          disconnectBtn.disabled = false;
          sendBtn.disabled = false;
          sendRequestBtn.disabled = false;
        });

        wsClient.on('message', (data) => {
          log(`收到消息: ${JSON.stringify(data)}`);
        });

        wsClient.on('error', (error) => {
          log(`错误: ${error.message}`, true);
        });

        wsClient.on('close', (event) => {
          log(`连接关闭: ${event.code} - ${event.reason}`);
          connectBtn.disabled = false;
          disconnectBtn.disabled = true;
          sendBtn.disabled = true;
          sendRequestBtn.disabled = true;
        });

        wsClient.on('reconnect_attempt', (attempt) => {
          log(`正在尝试重连 (第 ${attempt} 次)`);
        });

        wsClient.on('reconnect_failed', (attempts) => {
          log(`重连失败 (共尝试 ${attempts} 次)`, true);
        });
        wsClient.on('disconnecting_due_to_hidden', (attempts) => {
          console.info('disconnecting_due_to_hidden');
        });

        // 修改心跳事件监听
        wsClient.on('heartbeat', (info) => {
          if (info.direction === 'incoming') {
            log(
              `收到${info.type}: 来自服务器的${
                info.type === 'ping' ? '主动Ping' : 'Pong响应'
              }`
            );
          } else {
            log(`发送Ping: 客户端心跳包`);
          }
        });

        // 添加发送心跳日志
        wsClient.on('heartbeat_sent', () => {
          log('发送Ping: 客户端心跳包');
        });
      }

      init();

      // 连接按钮事件
      connectBtn.addEventListener('click', () => {
        init();
      });

      // 断开连接按钮事件
      disconnectBtn.addEventListener('click', () => {
        if (wsClient) {
          wsClient.close();
          wsClient = null;
        }
      });

      // 发送消息按钮事件
      sendBtn.addEventListener('click', () => {
        const message = messageInput.value;
        if (!message) return;

        try {
          // 尝试解析为JSON，如果失败则作为普通文本发送
          const data = JSON.parse(message);
          wsClient.send(data);
          log(`发送消息: ${JSON.stringify(data)}`);
        } catch {
          wsClient.send(message);
          log(`发送消息: ${message}`);
        }
        messageInput.value = '';
      });

      // 发送请求并等待响应按钮事件
      sendRequestBtn.addEventListener('click', async () => {
        const message = messageInput.value;
        if (!message) return;

        try {
          const data = JSON.parse(message);
          log(`发送请求: ${JSON.stringify(data)}`);
          const response = await wsClient.sendRequest(data, 3000);
          log(`收到响应: ${JSON.stringify(response)}`);
        } catch (error) {
          log(`请求失败: ${error.message}`, true);
        }
        messageInput.value = '';
      });

      // 允许按Enter键发送消息
      messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendBtn.click();
      });
    </script>
  </body>
</html>
